package com.mashibing.vector;

public class Binary_Search {
    int binarySearch(int arr[],int left, int right,int tar){
        if(right>=1){
            int mid=left+(right-1)/2;
            if(arr[mid]==tar)
                return mid;
            if(arr[mid]>tar)
                return binarySearch(arr,left,mid-1,tar);
            return binarySearch(arr,mid+1,right,tar);
        }
        return -1;
    }
    //区间左闭右闭
    int binarySearch1(int arr[],int tar){
        int left=0;
        int right=arr.length-1;
        int mid=(left+right)/2;
        while(left<=right){
            if(tar<arr[mid]){
                right=mid-1;
            }else if(tar>arr[mid]){
                left=mid+1;
            }else{
                return mid;
            }
        }
        return -1;
    }
    //区间左闭右开
    int binarySearch2(int arr[],int tar){
        int left=0;
        int right=arr.length;
        int mid=(left+right)/2;
        while(left<=right){
            if(tar<arr[mid]){
                right=mid;
            }else if(tar>arr[mid]){
                left=mid+1;
            }else{
                return mid;
            }
        }
        return -1;
    }
}
